package com.fingerth.crawler.utils.permission

import android.Manifest
import android.app.Activity
import android.app.AlertDialog
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import com.fingerth.crawler.BuildConfig
import java.util.*

class PermissionUtils {
    companion object {
        const val CODE_PERMISSION_WRITE_EXTERNAL_STORAGE = 124
        const val CODE_PERMISSION_CAMERA = 125
        const val CODE_PERMISSION_ACCESS_FINE_LOCATION = 126
        const val CODE_PERMISSION_ALL = 127
    }

    fun checkWriteExternalStorage(activity: Activity?): Boolean = check(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE)
    fun checkCamera(activity: Activity?): Boolean = check(activity, Manifest.permission.CAMERA)
    fun checkAccessFineLocation(activity: Activity?): Boolean = check(activity, Manifest.permission.ACCESS_FINE_LOCATION)
    private fun check(activity: Activity?, permission: String) = activity?.let { ContextCompat.checkSelfPermission(it, permission) == PackageManager.PERMISSION_GRANTED } ?: false

    fun requestWriteExternalStorage(activity: Activity?) {
        requestPermissions(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE, CODE_PERMISSION_WRITE_EXTERNAL_STORAGE)
        //TODO 在申請的Activity裡面的代碼
//        @Override
//        public void onRequestPermissionsResult(int permsRequestCode, String[] permissions, int[] grantResults) {
//            switch (permsRequestCode) {
//                case 200:
//
//                    boolean cameraAccepted = grantResults[0] == PackageManager.PERMISSION_GRANTED;
//                    if (cameraAccepted) {
//                        //授权成功之后
//                    } else {
//                        showOpenPermissionsDialog();
//                    }
//
//                    break;
//            }
//        }
    }

    fun requestCamera(activity: Activity?) = requestPermissions(activity, Manifest.permission.CAMERA, CODE_PERMISSION_CAMERA)
    fun requestLocation(activity: Activity?) = requestPermissions(activity, Manifest.permission.ACCESS_FINE_LOCATION, CODE_PERMISSION_ACCESS_FINE_LOCATION)


    private fun requestPermissions(activity: Activity?, permission: String, code: Int) {
        activity?.let {
            if (ContextCompat.checkSelfPermission(it, permission) != PackageManager.PERMISSION_GRANTED) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    val perms = arrayOf(permission)
                    activity.requestPermissions(perms, code)
                } else {
                    ActivityCompat.requestPermissions(it, arrayOf(permission), code)
                }
            }
        }
    }

    fun showOpenPermissionsDialog(act: Activity?, help: String? = "提示", msg: String?, setting: String? = "设置", cancel: String? = "取消") {
        act?.let { activity ->
            //用户授权拒绝之后，友情提示一下就可以了
            AlertDialog.Builder(activity).apply {
                setTitle(help) //设置标题
                setMessage(msg) //设置内容
                setPositiveButton(setting) { _, _ ->
                    activity.startActivity(Intent().apply {
                        action = "android.settings.APPLICATION_DETAILS_SETTINGS"
                        addCategory(Intent.CATEGORY_DEFAULT)
                        data = Uri.parse("package:${BuildConfig.APPLICATION_ID}") //包名
                    })
                    //activity.overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
                }
                setNegativeButton(cancel) { _, _ -> }
            }.create().let {
                it.setCanceledOnTouchOutside(false)
                it.show() //show（）
            }
        }
    }


    //============================================================================================
    //本項目所有需要動態申請的權限，一次申請===========================================================
    fun checkAllPermissions(activity: Activity?) {
        activity?.let {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                val permissions = ArrayList<String>()
//                if (!check(it, Manifest.permission.ACCESS_FINE_LOCATION)) permissions.add(Manifest.permission.ACCESS_FINE_LOCATION)
                //if (!checkCamera(it)) permissions.add(Manifest.permission.CAMERA)
                if (!checkWriteExternalStorage(it)) permissions.add(Manifest.permission.WRITE_EXTERNAL_STORAGE)
//                if (!check(it, Manifest.permission.READ_PHONE_STATE)) permissions.add(Manifest.permission.READ_PHONE_STATE)
                if (permissions.size > 0) activity.requestPermissions(permissions.toTypedArray(), CODE_PERMISSION_ALL)
            }
        }
    }

    //本項目所有需要動態申請的權限，一次申請===========================================================
    //============================================================================================


}